#!/bin/bash
# 1.备份目录1
CURRENT_DIR=$(cd $(dirname $0); pwd)
BACKUP=${CURRENT_DIR}/back/
# 当前时间
DATETIME=$(date +%Y-%m-%d_%H%M%S)
echo $DATETIME
CONTAINER_NAME=mysql_db_1
# 数据库的用户名
DB_USER=root
#数据库的密码
DB_PW=123456

#创建备份目录 如果不存在就创建
[ ! -d "${BACKUP}/${DATETIME}" ] && mkdir -p "${BACKUP}/${DATETIME}"

# 备份数据库

for DATABASE in `docker exec ${CONTAINER_NAME} sh -c ' exec mysql -u'${DB_USER}' -p'${DB_PW}' -e "show databases;"'|grep -Evi "sys|_schema|mysql|Database"`

do
  docker exec ${CONTAINER_NAME} sh -c ' exec mysqldump  -u'${DB_USER}' -p'${DB_PW}' -q -R --databases '${DATABASE}' | gzip' > ${BACKUP}/${DATETIME}/$DATABASE.sql.gz
done
# 将文件处理成 tar.gz
cd ${BACKUP}
tar -zcvf $DATETIME.tar.gz ${DATETIME}
# 删除对应的备份目录
rm -rf ${BACKUP}/${DATETIME}

# 删除十天前的备份文件
find ${BACKUP} -atime +10 -name "*.tar.gz" -exec rm -rf {} \;
echo "备份数据库${DATABASE} 成功"